package com.ciwong.epaper.modules.bookstore.ui;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.bookstore.adapter.BookStoreAdapter;
import com.ciwong.epaper.modules.bookstore.bean.BookstoreDataBean;
import com.ciwong.epaper.modules.bookstore.dao.BookstoreDao;
import com.ciwong.epaper.modules.epaper.bean.Grade;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.widget.GradeSelectDialog;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.epaper.widget.RecycleViewDivider;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;


/**
 * 教辅书城fragment
 * Created by luojinlei on 2017/12/19.
 */

public class BookstoreFragment extends BaseFragment implements PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener, View.OnClickListener {
    private static final String TAG = "BookstoreFragment";

    /**
     * //	 * 选择班级部分
     */
    private View rootView;

    private ImageButton btnSelectGrade;
    private TextView tvGrade;


    private RecyclerView recyclerView;

    private PullToRefreshView pullToRefreshView;

    private BookStoreAdapter mBookStoreAdapter;
    private boolean isChectSlectGarade;

    private RelativeLayout ib_search;
    private ImageButton img_btn_search;
    private View btn_select_grade;

    private Handler handler = new Handler();
    /**
     * 是否是刷新状态,true为刷新，false为加载更多
     */
    private boolean isRefresh = true;
    private boolean isNoMoreData = false;

    /**
     * 获取BookstoreFragment实例
     *
     * @return
     */
    public static BookstoreFragment newInstance() {
        BookstoreFragment bookstoreFragment = new BookstoreFragment();
        return bookstoreFragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_bookstore, container, false);
        findViews();
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        loadLocalData();
    }

    private void findViews() {
        recyclerView = (RecyclerView) rootView.findViewById(R.id.swipe_target);
        recyclerView.setNestedScrollingEnabled(false);
        pullToRefreshView = (PullToRefreshView) rootView.findViewById(R.id.ptr_bookstore_fragment);
        tvGrade = rootView.findViewById(R.id.tv_grade);
        ib_search = (RelativeLayout) rootView.findViewById(R.id.ib_search);
        img_btn_search = (ImageButton) rootView.findViewById(R.id.img_btn_search);
        btnSelectGrade = (ImageButton) rootView.findViewById(R.id.ib_go2grade);
        btn_select_grade = rootView.findViewById(R.id.btn_select_grade);


    }

    private void init() {
        mBookStoreAdapter = new BookStoreAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(mBookStoreAdapter);
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, DisplayUtils.dip2px(getActivity().getApplicationContext(), 8), getResources().getColor(R.color.light_gray6)));
        ib_search.setOnClickListener(this);
        img_btn_search.setOnClickListener(this);
        tvGrade.setText(EApplication.getInstance().getGrade().getGradeName());
        tvGrade.setOnClickListener(this);
        btnSelectGrade.setOnClickListener(this);
        btn_select_grade.setOnClickListener(this);

        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        //		pullToRefreshView.setEnablePullLoadMoreDataStatus(false);
    }


    private void loadNetData() {
        CWLog.d(TAG, "loadNetData" + "bookfragment");
        if (!NetworkUtils.isOnline()) {
           ToastUtil.INSTANCE.toastCenterNoNetError();
            //			swipeToLoadLayout.setRefreshing(false);
            pullToRefreshView.onHeaderRefreshComplete();
            pullToRefreshView.onFooterRefreshComplete();
        } else {
            int schoolId = 0;
            int gradeId = 0;
            String areaId = "0";
            gradeId = EApplication.getInstance().getGrade().getGradeId();
            /*;
            SchoolDetail schoolDetail = EApplication.getInstance().getSchoolDetail();
			if (null != schoolDetail) {
				schoolId = schoolDetail.getSchoolId();
				areaId = schoolDetail.getAreaCode();
			}*/

            Clazz clazz = EApplication.getInstance().getClazz();
            if (clazz != null) {
                //				gradeId = clazz.getGradeId();
                areaId = clazz.getSchoolArea();
                schoolId = clazz.getSchoolID();

            }
            Log.d(TAG, "######areaId########" + areaId);
            Log.d(TAG, "######gradeId########" + gradeId);
            Log.d(TAG, "######schoolId########" + schoolId);
            Log.d(TAG, "######getActivity()########" + getActivity());

            BookstoreDao.getInstance().getFirstPage(EApplication.BRAND_ID, areaId, gradeId, schoolId, new BaseExtCallBack(getActivity()) {
                /**
                 * @param data
                 */
                @Override
                public void success(Object data) {
                    super.success(data);
                    BookstoreDataBean bookstoreDataBean = (BookstoreDataBean) data;

                    if (bookstoreDataBean != null) {
                        mBookStoreAdapter.setBookstoreDataBean(bookstoreDataBean);
                        isNoMoreData = true;
                        // 保存本地数据
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_BOOKSTORE_LIST,
                                (Serializable) bookstoreDataBean);

                    }
                    loadOver();
                }

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(R.string.connect_server_error,errorCode);
                    isNoMoreData = false;
                    loadOver();
                }

                @Override
                public void failed(Object data) {
                    super.failed(data);
                    isNoMoreData = false;
                    loadOver();
                    ToastUtil.INSTANCE.toastCenterError( R.string.connect_server_error);
                }
            });
        }
    }


    /**
     * 添加本地数据
     */
    private void loadLocalData() {
        CWLog.d(TAG, "loadLocalData" + "bookfragment");
        //		this.showCricleProgress();
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_BOOKSTORE_LIST,
                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        if (data != null) {
                            BookstoreDataBean bookstoreDataBean = (BookstoreDataBean) data;
                            mBookStoreAdapter.setBookstoreDataBean(bookstoreDataBean);
                        }

                        //						hideCricleProgress();
                        loadNetData();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        //						hideCricleProgress();
                        loadNetData();
                    }

                    @Override
                    public void failed(Object data) {
                        //						hideCricleProgress();
                        loadNetData();
                    }
                });
    }

    /**
     * //	 * 跳到选择年级对话框
     */
    private void jumpToSelectGradDialog() {
        GradeSelectDialog gradeSelectDialog = new GradeSelectDialog(getActivity(), new GradeSelectDialog.OnGradeSelectListener() {
            @Override
            public void onGradeSelect(int gradeId, String gradeName) {
                tvGrade.setText(gradeName);
                Grade grade = new Grade();
                grade.setGradeId(gradeId);
                grade.setGradeName(gradeName);
                EApplication.getInstance().setGrade(grade);
                loadNetData();
            }
        });
        gradeSelectDialog.show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        if (id == R.id.ib_search || id == R.id.img_btn_search) {
            EpaperJumpManager.jumpToShopSerachBook(R.string.go_back, mActivity, -1);
        } else if (id == R.id.tv_grade || id == R.id.ib_go2grade || id == R.id.btn_select_grade) {
            jumpToSelectGradDialog();
        }
    }

    /**
     * 加载完成
     */
    private void loadOver() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isRefresh) {
                    pullToRefreshView.onHeaderRefreshComplete();
                    if (isNoMoreData) {
                        pullToRefreshView.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                    }
                } else {
                    pullToRefreshView.onFooterRefreshComplete();
                }
            }
        }, 500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        loadNetData();
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.onFooterRefreshComplete();
        pullToRefreshView.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
    }

    public void checkSlectedGrade() {
        CWLog.d(TAG, "checkSlectedGrade" + "bookfragment");
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        } else {
            if (!isChectSlectGarade) {
                isChectSlectGarade = true;
                Grade grade = null;
                String gradeKey = SerializableManager.SerializeKey.SHARE_KEY_GRADE_ID + SerializableManager.getInstance().getUserId(true);
                Log.d(TAG, "#########gradeKey###########" + gradeKey);
                try {
                    grade = (Grade) CWSys.getSharedSerializable(gradeKey);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (null == grade) {
                    Log.d(TAG, "#########null==grade##########");

                    MeDao.getInstance().getClassList(EApplication.BRAND_ID,
                            new BaseCallBack() {
                                @Override
                                public void success(Object data) {
                                    final List<Clazz> clazzs = (List<Clazz>) data;
                                    //没有年级但是有班级
                                    if (null != clazzs && clazzs.size() > 0) {
                                        Clazz clazz = EApplication.getInstance().getClazz();
                                        if (clazzs == null || clazzs.isEmpty()) {
                                            clazz = null;
                                        } else {
                                            int indexOf = clazzs.indexOf(clazz);
                                            if (indexOf < 0) {
                                                indexOf = 0;
                                            }
                                            clazz = clazzs.get(indexOf);
                                        }

                                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, clazz);
                                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, (Serializable) clazzs);
                                        EApplication.getInstance().setClazzs(clazzs);
                                        EApplication.getInstance().setClazz(clazz);
                                        int gradeId = clazz.getGradeId();
                                        String areaId = clazz.getSchoolArea();
                                        int schoolId = clazz.getSchoolID();
                                        Log.d(TAG, "#########gradeId233##########" + clazz.getGradeId());
                                        Log.d(TAG, "#########areaId233##########" + clazz.getSchoolArea());
                                        Log.d(TAG, "#########schoolId233##########" + clazz.getSchoolID());
                                        Grade grade = new Grade();
                                        grade.setGradeId(gradeId);
                                        grade.setGradeName(GradeSelectDialog.getGradeNameById(gradeId));
                                        EApplication.getInstance().setGrade(grade);
                                        tvGrade.setText(GradeSelectDialog.getGradeNameById(gradeId));


                                        BookstoreDao.getInstance().getFirstPage(EApplication.BRAND_ID, areaId, gradeId, schoolId, new BaseExtCallBack(getActivity()) {
                                            @Override
                                            public void success(Object data) {
                                                super.success(data);
                                                BookstoreDataBean bookstoreDataBean = (BookstoreDataBean) data;
                                                if (bookstoreDataBean != null) {
                                                    mBookStoreAdapter.setBookstoreDataBean(bookstoreDataBean);
                                                    // 保存本地数据
                                                    SerializableManager.getInstance().serialize(
                                                            SerializableManager.SerializeKey.SHARE_KEY_BOOKSTORE_LIST,
                                                            (Serializable) bookstoreDataBean);
                                                }
                                            }

                                            @Override
                                            public void failed(int errorCode, Object data) {
                                                super.failed(errorCode, data);
                                                ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(R.string.connect_server_error,errorCode);
                                            }

                                            @Override
                                            public void failed(Object data) {
                                                super.failed(data);
                                                ToastUtil.INSTANCE.toastCenterError(R.string.connect_server_error);
                                            }
                                        });

                                    } else {
                                        //没有缓存且没有班级才要弹
                                        Grade grade = new Grade();
                                        grade.setGradeId(0);
                                        grade.setGradeName("range_all");
                                        EApplication.getInstance().setGrade(grade);
                                        jumpToSelectGradDialog();
                                    }
                                }

                                @Override
                                public void failed(int errorCode, Object data) {
                                    CWLog.d(TAG, "拉取班级列表失败:" + errorCode);
                                }

                                @Override
                                public void failed(Object data) {
                                    CWLog.d(TAG, "拉取班级列表失败:" + data);
                                }
                            });
                } else {
                    //有年级
                    Log.d(TAG, "#########null!=grade##########" + grade.getGradeName());
                    tvGrade.setText(grade.getGradeName());
                    loadNetData();
                }
            } else {
                //已经检查过年级，即已经选择过年级了
                loadLocalData();
            }
        }
    }

}
